<?
class ip {
	
	
	public function getCityFromIP($ip)
	{
		if (!$data=$this->getCityFromCookies())
		{
			if (is_array($data=$this->getCityFromMySQL($ip)))
			{
				setcookie("CCC", $data['contry_id'].':'.$data['state_id'].':'.$data['city_id'], time()+3600*24*365);
			}
		}
		if (count($data))
		{
			define('IP_CITY_ID',$data['city_id']);
			define('IP_COUNTRY_ID',$data['contry_id']);
			define('IP_STATE_ID',$data['state_id']);
		}
	}
	
	protected function getCityFromMySQL($ip)
	{
		$ip_manager = new IpCoreManager();
		if (is_array($data=$ip_manager->getCityIp($ip)))
		{
			return $data;
		}
		$ip_manager->insertIpTemp($ip);
		return false;
	}
	
	protected function getCityFromCookies()
	{
		if ($_COOKIE['CCC']!='')
		{
			$arr=explode(':',$_COOKIE['CCC']);
			if ($arr[1]*1<0)
			{
				$arr[1]=0;
			}
			if ($arr[2]*1<0)
			{
				$arr[2]=0;
			}
			if ($arr[0]==222 && $arr[2]<0)
			{
				return false;
			}else {
				return array('contry_id'=>$arr[0]*1,'state_id'=>$arr[1]*1,'city_id'=>$arr[2]*1);
			}
		}
		return false;
	}
}
?>